package com.xzjt.web.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.xzjt.common.components.RedisService;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.exception.InvalidTokenException;
import com.xzjt.web.mapper.SysUserMapper;
import com.xzjt.web.service.AuthcService;
import com.xzjt.web.config.JwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName: AuthcServiceImpl
 * @Author: yuandong
 * @Date 2021/10/8 14:06
 */
@Slf4j
@Service
public class AuthcServiceImpl implements AuthcService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtService jwtService;

    @Override
    public SysUser selectUserByName(String username) {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        return sysUser;
    }


    /**
     * 验证token(UserRealm中)
     * @param token
     */
    @Override
    public void validateToken(String token)  {

        // 先校验缓存中Token是否存在，缓存中不存在Token说明Token已失效，需要重新登录
        SysUser sysUser =(SysUser)  redisService.get(token);
        if (sysUser==null) {
            //token过期
            throw new InvalidTokenException();
        }


        //验证token是否正确
        if(!jwtService.verify(token, sysUser.getUsername())){
            throw new InvalidTokenException();
        }

        //更新token的有效期
        long tokenExpireTime = 1 ;
        JSONObject obj = new JSONObject();
        obj.put("sysUser", sysUser);
        redisService.expire(token,tokenExpireTime); //单位是分钟

        long expire = redisService.getExpire(token);
        log.info("当前用户的token值为是：{}",token);
        log.info("当前用户redis中的过期时间是：{} 分钟",expire);

    }
}
